<!--  -->
<template>
  <div class="">
    <crumb  title="首页" title2="商品管理" title3="参数列表"></crumb >
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-row type="flex" justify="start" align="middle">
        <el-col :span="3"><div>选择商品分类：</div></el-col>
        <el-col :span="7" :pull="1">
          <el-cascader
            v-model="checkboxID"
            :options="options"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isButn" @click="addparams" class="btn"
            >添加参数</el-button
          >
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="tag"
                  v-for="(tag, index) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scope.row, index)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" @click="handleUpdate(scope.row)"
                  >编辑</el-button
                >
                <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isButn" @click="addparams" class="btn"
            >添加属性</el-button
          >
          <el-table :data="onlyTable" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="tag"
                  v-for="(tag, index) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scope.row, index)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" @click="handleUpdate(scope.row)"
                  >编辑</el-button
                >
                <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      :title="'修改' + tititleText"
      :visible.sync="dialogVisible"
      width="50%"
      @close="upadhuang"
    >
      <el-form
        :model="upadTabe"
        :rules="upadrules"
        ref="upadruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="tititleText" prop="attr_name">
          <el-input v-model="upadTabe.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="equest">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="'添加' + tititleText"
      :visible.sync="ADDdialogVisible"
      width="50%"
      @close="addhuang"
    >
      <el-form
        :model="adddTabe"
        :rules="addrules"
        ref="addruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="tititleText" prop="attr_name">
          <el-input v-model="adddTabe.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addequest">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      dialogVisible: false,
      inputVisible: false,
      ADDdialogVisible: false,
      inputValue: "",
      checkboxID: [],
      onlyTable: [],
      activeName: "many",
      options: [],
      manyTableData: [],
      cateProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      upadTabe: {
        attr_name: "",
      },
      adddTabe: {
        attr_name: "",
      },
      upadrules: {
        attr_name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
      addrules: {
        attr_name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
    };
  },
  //监听属性 类似于data概念
  computed: {
    cateId() {
      if (this.checkboxID.length === 3) {
        return this.checkboxID[2];
      }
      return null;
    },
    isButn() {
      if (this.checkboxID.length !== 3) {
        return true;
      }
      return false;
    },
    tititleText() {
      if (this.activeName == "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    addparams() {
      this.ADDdialogVisible = true;
    },
    //清空
    upadhuang() {
      this.$refs.upadruleForm.resetFields();
    },
    addhuang() {
      this.$refs.addruleForm.resetFields();
    },
    //选中分类获取数据
    handleChange() {
      // console.log(this.checkboxID)
      this.getParams();
    },
    async getParams() {
      const { data: res } = await this.myaxios.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (res.meta.status !== 200) {
        return this.$message("获取参数失败");
      }

      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTable = res.data;
      }
    },
    //获取分类数据
    async addSer() {
      const { data: res } = await this.myaxios.get("categories");
      console.log(res);
      this.options = res.data;
    },
    handleClick() {
      if (this.cateId != null) {
        this.getParams();
      }
    },
    //编辑
    async handleUpdate(row) {
      this.dialogVisible = true;
      console.log();
      const { data: res } = await this.myaxios.get(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          params: { attr_sel: this.activeName },
        }
      );
      this.upadTabe.attr_id = row.attr_id;
      this.upadTabe.attr_name = row.attr_name;
      this.upadTabe.attr_vals = row.attr_vals;
    },
    //确定
    equest() {
      this.$refs.upadruleForm.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.myaxios.put(
          `categories/${this.cateId}/attributes/${this.upadTabe.attr_id}`,
          {
            attr_name: this.upadTabe.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.upadTabe.attr_vals.join(" "),
          }
        );
        console.log(this.upadTabe.attr_id);
        this.$message.success("修改成功");
        this.getParams();
        this.dialogVisible = false;
      });
    },
    addequest() {
      this.$refs.addruleForm.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.myaxios.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.adddTabe.attr_name,
            attr_sel: this.activeName,
          }
        );
        this.$message.success("添加成功");
        this.getParams();
        this.ADDdialogVisible = false;
      });
    },
    //删除
    async handleDelete(row) {
      const { data: res } = await this.myaxios.delete(
        `categories/${this.cateId}/attributes/${row.attr_id}`
      );
      if (res.meta.status !== 200) {
        this.$message.error("删除失败");
      }
      this.getParams()
      this.$message.success("删除成功");
      
    },
    handleClose(row, i) {
      row.attr_vals.splice(i, 1);
      this.saveAttrVals(row);
    },
    async saveAttrVals(row) {
      const { data: res } = await this.myaxios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      // console.log(row.attr_vals.join(" "));
      this.$message.success("修改参数成功");
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm(row) {
      // let inputValue = row.inputValue;
      // if (inputValue) {
      //   this.dynamicTags.push(inputValue);
      // }
      // row.inputVisible = false;
      // row.inputValue = "";
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.saveAttrVals(row);
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.addSer();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
.el-row {
  margin: 20px;
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.btn{
  margin:20px;
}
</style>
